<template>
  <div class="school-members">
    <div class="section-header">
      <h2 class="section-title">成员管理</h2>
      <div class="filters">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名称"
          class="search-input"
          clearable
          @input="applyFilters"
        >
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
        <el-select v-model="roleFilter" placeholder="角色筛选" @change="applyFilters">
          <el-option label="全部" value="all"></el-option>
          <el-option label="管理员" value="admin"></el-option>
          <el-option label="学生" value="student"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 成员列表 -->
    <el-table
      v-loading="loading"
      :data="pagedMembers"
      style="width: 100%"
      stripe
      row-key="_id"
      empty-text="暂无成员数据"
    >
      <el-table-column type="index" label="#" width="60"></el-table-column>

      <el-table-column prop="avatar" label="头像" width="80">
        <template #default="scope">
          <img
            :src="scope.row.avatar ? `http://localhost:5000/uploads/${scope.row.avatar}` : defaultTouxiang"
            alt="头像"
            class="member-avatar"
          />
        </template>
      </el-table-column>

      <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>

      <el-table-column prop="phone" label="联系方式" min-width="120">
        <template #default="scope">
          {{ scope.row.phone || '未设置' }}
        </template>
      </el-table-column>

      <el-table-column prop="isAdmin" label="角色" width="100">
        <template #default="scope">
          <el-tag type="success" v-if="isAdmin(scope.row)">管理员</el-tag>
          <el-tag v-else>学生</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="joinDate" label="加入时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.registration_time) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="260" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="info"
            @click="viewMemberDetails(scope.row)"
          >
            详情
          </el-button>
          <el-button
            size="small"
            :type="isAdmin(scope.row) ? 'warning' : 'success'"
            @click="toggleAdminStatus(scope.row)"
            :disabled="isCurrentUser(scope.row._id)"
          >
            {{ isAdmin(scope.row) ? '取消管理' : '设为管理' }}
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="confirmRemoveMember(scope.row)"
            :disabled="isCurrentUser(scope.row._id)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, total"
        :total="totalFilteredMembers"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 成员详情对话框 -->
    <el-dialog title="成员详情" v-model="detailsDialogVisible" width="400px">
      <div v-if="selectedMember">
        <p><strong>用户名:</strong> {{ selectedMember.username }}</p>
        <p><strong>联系方式:</strong> {{ selectedMember.phone || '未设置' }}</p>
        <p><strong>加入时间:</strong> {{ formatDate(selectedMember.registration_time) }}</p>
        <p><strong>角色:</strong> {{ isAdmin(selectedMember) ? '管理员' : '学生' }}</p>
        <!-- 可以根据需要从后端获取更多信息展示 -->
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  schoolId: {
    type: String,
    required: true
  }
})
const defaultTouxiang = '/src/assets/touxiang.png'
// 数据状态
const allMembers = ref([])
const filteredMembers = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')
const roleFilter = ref('all')
const currentUser = ref(null)
const schoolAdmins = ref([])

// 详情对话框
const detailsDialogVisible = ref(false)
const selectedMember = ref(null)

// 计算属性：当前页应显示的成员
const pagedMembers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredMembers.value.slice(start, end)
})

// 计算属性：筛选后的总成员数
const totalFilteredMembers = computed(() => filteredMembers.value.length)

// 监听schoolId变化，重新加载数据
watch(() => props.schoolId, (newValue) => {
  if (newValue) {
    fetchInitialData()
  }
})

// 获取当前用户信息
const fetchCurrentUser = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) return;
    const response = await axios.get('http://localhost:5000/users/me', {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    currentUser.value = response.data
  } catch (error) {
    console.error('获取当前用户信息失败:', error)
  }
}

// 获取学校成员和管理员列表
const fetchInitialData = async () => {
  if (!props.schoolId) return

  loading.value = true
  try {
    await fetchCurrentUser()

    const response = await axios.get(`http://localhost:5000/schools/${props.schoolId}/users`)

    if (response.data && response.data.users) {
      allMembers.value = response.data.users
      schoolAdmins.value = response.data.schoolAdmins || []
      applyFilters()
    } else {
      allMembers.value = []
      filteredMembers.value = []
      schoolAdmins.value = []
    }
  } catch (error) {
    console.error('获取学校成员数据失败:', error)
    ElMessage.error('获取学校成员数据失败: ' + (error.response?.data?.message || error.message))
    allMembers.value = []
    filteredMembers.value = []
    schoolAdmins.value = []
  } finally {
    loading.value = false
  }
}

// 应用筛选和搜索
const applyFilters = () => {
  let tempMembers = allMembers.value

  if (roleFilter.value === 'admin') {
    tempMembers = tempMembers.filter(member => isAdmin(member))
  } else if (roleFilter.value === 'student') {
    tempMembers = tempMembers.filter(member => !isAdmin(member))
  }

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    tempMembers = tempMembers.filter(member =>
      (member.username && member.username.toLowerCase().includes(query)) ||
      (member.phone && member.phone.includes(query))
    )
  }

  filteredMembers.value = tempMembers
  currentPage.value = 1
}

// 检查用户是否是管理员
const isAdmin = (user) => {
  return schoolAdmins.value.some(adminId => adminId === user._id)
}

// 检查是否是当前用户
const isCurrentUser = (userId) => {
  return currentUser.value && currentUser.value._id === userId
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  if (isNaN(date.getTime())) {
      return '无效日期';
  }
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
}

// 查看成员详情
const viewMemberDetails = (user) => {
  selectedMember.value = user
  detailsDialogVisible.value = true
}

// 切换管理员状态
const toggleAdminStatus = async (user) => {
  const action = isAdmin(user) ? '取消' : '设置'
  const actionVerb = isAdmin(user) ? 'delete' : 'put'
  const url = `http://localhost:5000/schools/${props.schoolId}/admins/${user._id}`

  try {
    await ElMessageBox.confirm(
      `确定要${action}${user.username}的管理员权限吗？`,
      `${action}管理员`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const token = localStorage.getItem('token')
    if (!token) {
        ElMessage.warning('请先登录');
        return;
    }

    const response = await axios({
        method: actionVerb,
        url: url,
        headers: { 'Authorization': `Bearer ${token}` }
    });

    schoolAdmins.value = response.data.admins || []
    applyFilters()

    ElMessage.success(`${action}${user.username}的管理员权限成功`)

  } catch (error) {
    if (error === 'cancel') return
    console.error(`${action}管理员权限失败:`, error)
    ElMessage.error(`${action}管理员权限失败: ` + (error.response?.data?.message || error.message))
  }
}

// 确认移除成员
const confirmRemoveMember = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要将 ${user.username} 从学校中移除吗？该操作将同时将其从学校所有社团中移除。`,
      '移除成员',
      {
        confirmButtonText: '确定移除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const token = localStorage.getItem('token')
    if (!token) {
        ElMessage.warning('请先登录');
        return;
    }

    await axios.delete(`http://localhost:5000/schools/${props.schoolId}/users/${user._id}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    })

    ElMessage.success(`已将 ${user.username} 从学校中移除`)
    allMembers.value = allMembers.value.filter(m => m._id !== user._id)
    applyFilters()

  } catch (error) {
    if (error === 'cancel') return
    console.error('移除成员失败:', error)
    ElMessage.error('移除成员失败: ' + (error.response?.data?.message || error.message))
  }
}

// 组件挂载时获取初始数据
onMounted(() => {
  if (props.schoolId) {
    fetchInitialData()
  }
})
</script>

<style scoped>
.school-members {
  padding: 20px 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  color: #fff;
  font-size: 24px;
  margin: 0;
}

.filters {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.member-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

/* Element Plus 组件样式重写 */
:deep(.el-table) {
  background-color: transparent;
  color: #eee;
}

:deep(.el-table th) {
  background-color: #1f1b24;
  color: #b0bec5;
  border-bottom-color: #333;
}

:deep(.el-table tr) {
  background-color: #28232e;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #23202a;
}

:deep(.el-table td) {
  border-bottom-color: #333;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #342e3d;
}

:deep(.el-select) {
  width: 120px;
}

:deep(.el-input__inner), :deep(.el-textarea__inner) {
  background-color: #1f1b24;
  border-color: #444;
  color: #fff;
}

:deep(.el-input__inner:focus), :deep(.el-textarea__inner:focus) {
  border-color: #00aeff;
}

:deep(.el-select-dropdown) {
  background-color: #1f1b24;
  border-color: #444;
}

:deep(.el-select-dropdown__item) {
  color: #eee;
}

:deep(.el-select-dropdown__item.hover, .el-select-dropdown__item:hover) {
  background-color: #28232e;
}

:deep(.el-button) {
  margin-left: 5px;
}

:deep(.el-table__empty-text) {
  color: #777;
}

.filters .search-input {
    margin-right: 10px;
}

:deep(.el-table__body-wrapper .el-table__cell:last-child .cell) {
    display: flex;
    gap: 5px;
}
</style>
